import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { NavBar, Card, List, Button, Tag, Empty, PullToRefresh } from 'antd-mobile';
import { 
  EyeOutline, 
  EyeInvisibleOutline, 
  RightOutline,
  HistogramOutline,
  HeartOutline,
  CouponOutline,
  CheckCircleOutline,
  PayCircleOutline
} from 'antd-mobile-icons';
import axios from '../../axios';
import './Com/Money.css';

// 用户数据类型
interface UserInfo {
  id: string;
  nickname: string;
  avatar: string;
  wallet: {
    balance: number;
    redPackets: number;
    bonus: number;
  };
  orders: Order[];
  coupons: Coupon[];
  redPacketHistory: RedPacketHistory[];
}

// 订单数据类型
interface Order {
  orderId: string;
  productName: string;
  price: number;
  quantity: number;
  status: string;
  orderTime: string;
  paymentMethod: string;
  deliveryAddress: string;
  completedTime?: string;
  refundAmount?: number;
  refundTime?: string;
}

// 优惠券数据类型
interface Coupon {
  id: string;
  name: string;
  discount: number;
  status: string;
  startTime: string;
  endTime: string;
  usedTime?: string;
}

// 红包历史数据类型
interface RedPacketHistory {
  id: string;
  date: string;
  amount: number;
  status: string;
}

// 交易记录类型
interface TransactionRecord {
  id: string;
  type: 'income' | 'expense' | 'refund' | 'redpacket' | 'coupon';
  amount: number;
  title: string;
  subtitle: string;
  time: string;
  status: string;
  icon: React.ReactNode;
  color: string;
}

const Money: React.FC = () => {
  const navigate = useNavigate();
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [showBalance, setShowBalance] = useState(true);
  const [transactionRecords, setTransactionRecords] = useState<TransactionRecord[]>([]);

  const handleBack = () => {
    navigate('/app/my');
  };

  // 获取用户数据
  const fetchUserData = async () => {
    try {
      const yonghuId = localStorage.getItem('yonghuId');
      if (!yonghuId) {
        console.error('未找到用户ID');
        return;
      }

      const response = await axios.get(`http://localhost:3000/hy/yonghu/${yonghuId}`);
      if (response.data.code === 200 && response.data.data) {
        setUserInfo(response.data.data);
        generateTransactionRecords(response.data.data);
      }
    } catch (error) {
      console.error('获取用户数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 生成交易记录
  const generateTransactionRecords = (userData: UserInfo) => {
    const records: TransactionRecord[] = [];

    // 订单交易记录
    userData.orders.forEach(order => {
      // 支付记录
      if (order.status !== '待付款') {
        records.push({
          id: `order_${order.orderId}`,
          type: 'expense',
          amount: order.price * order.quantity,
          title: '订单支付',
          subtitle: order.productName,
          time: order.orderTime,
          status: '已支付',
          icon: <PayCircleOutline />,
          color: '#f5222d'
        });
      }

      // 退款记录
      if (order.refundAmount && order.refundTime) {
        records.push({
          id: `refund_${order.orderId}`,
          type: 'refund',
          amount: order.refundAmount,
          title: '订单退款',
          subtitle: order.productName,
          time: order.refundTime,
          status: '已退款',
          icon: <CheckCircleOutline />,
          color: '#52c41a'
        });
      }
    });

    // 红包记录
    userData.redPacketHistory.forEach(redPacket => {
      records.push({
        id: `redpacket_${redPacket.id}`,
        type: 'redpacket',
        amount: redPacket.amount,
        title: '红包收入',
        subtitle: '天天领红包',
        time: redPacket.date,
        status: redPacket.status === '可使用' ? '已入账' : '已使用',
        icon: <HeartOutline />,
        color: '#ff4757'
      });
    });

    // 优惠券使用记录
    userData.coupons.forEach(coupon => {
      if (coupon.status === '已使用' && coupon.usedTime) {
        records.push({
          id: `coupon_${coupon.id}`,
          type: 'coupon',
          amount: coupon.discount,
          title: '优惠券抵扣',
          subtitle: coupon.name,
          time: coupon.usedTime,
          status: '已使用',
          icon: <CouponOutline />,
          color: '#faad14'
        });
      }
    });

    // 按时间排序
    records.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime());
    setTransactionRecords(records);
  };

  useEffect(() => {
    fetchUserData();
  }, []);

  const toggleBalanceVisibility = () => {
    setShowBalance(!showBalance);
  };

  const formatAmount = (amount: number) => {
    return showBalance ? `¥${amount.toFixed(2)}` : '***.**';
  };

  const formatTime = (timeString: string) => {
    const date = new Date(timeString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) {
      return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    } else if (days === 1) {
      return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
    }
  };



  const handleMoreDetails = () => {
    // 更多明细功能待开发
    console.log('更多明细');
  };

  if (loading) {
    return <div className="money-loading">正在加载...</div>;
  }

  if (!userInfo) {
    return <div className="money-error">用户信息获取失败</div>;
  }

  return (
    <div className="money-container">
      <NavBar onBack={handleBack} className="money-navbar">
        我的钱包
      </NavBar>

      <PullToRefresh onRefresh={fetchUserData}>
        <div className="money-content">
          {/* 余额展示区域 */}
          <Card className="balance-card">
            <div className="balance-header">
              <div className="balance-title">
                <span>钱包余额</span>
                <div className="balance-toggle" onClick={toggleBalanceVisibility}>
                  {showBalance ? <EyeOutline /> : <EyeInvisibleOutline />}
                </div>
              </div>
              <div className="balance-amount">
                {formatAmount(userInfo.wallet.balance)}
              </div>
            </div>
            

          </Card>



          {/* 交易明细 */}
          <Card className="transaction-card">
            <div className="transaction-header">
              <div className="transaction-title">
                <HistogramOutline />
                <span>交易明细</span>
              </div>
              <Button 
                fill="none" 
                size="small" 
                onClick={handleMoreDetails}
                className="more-btn"
              >
                查看更多 <RightOutline />
              </Button>
            </div>

            <div className="transaction-list">
              {transactionRecords.length > 0 ? (
                <List>
                  {transactionRecords.slice(0, 10).map((record) => (
                    <List.Item
                      key={record.id}
                      prefix={
                        <div className="transaction-icon" style={{ color: record.color }}>
                          {record.icon}
                        </div>
                      }
                      description={
                        <div className="transaction-info">
                          <div className="transaction-subtitle">{record.subtitle}</div>
                          <div className="transaction-time">{formatTime(record.time)}</div>
                        </div>
                      }
                      extra={
                        <div className="transaction-amount-section">
                          <div 
                            className={`transaction-amount ${record.type === 'income' || record.type === 'refund' || record.type === 'redpacket' ? 'income' : 'expense'}`}
                          >
                            {record.type === 'income' || record.type === 'refund' || record.type === 'redpacket' ? '+' : '-'}
                            {formatAmount(record.amount)}
                          </div>
                          <Tag 
                            color={record.status === '已支付' || record.status === '已入账' ? 'success' : 'default'}
                            className="transaction-status"
                          >
                            {record.status}
                          </Tag>
                        </div>
                      }
                    >
                      <div className="transaction-title">{record.title}</div>
                    </List.Item>
                  ))}
                </List>
              ) : (
                <Empty
                  image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
                  imageStyle={{ width: 128, height: 128 }}
                  description="暂无交易记录"
                />
              )}
            </div>
          </Card>
        </div>
      </PullToRefresh>
    </div>
  );
};

export default Money;
